package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import engine.Logger;

public class ThresholdWindow extends JFrame implements ChangeListener{

	private final String PREFS_PATH = "prefs"; 
	
	JTextField progress;
	int val;
	
	public ThresholdWindow() {
		setTitle("Threshold");
		
		val = ThresholdPrefs.get(50);
		
		progress = new JTextField("%");
		progress.setEditable(false);
		progress.setHorizontalAlignment(JTextField.CENTER);
		
		
		JSlider jl = new JSlider(0, 100);
		
		jl.addChangeListener(this);
		jl.setValue(val);
		setLayout(new BorderLayout());
		
		add(jl, BorderLayout.NORTH);
		
		
		add(progress, BorderLayout.CENTER);
		
		
		JPanel buttons = new JPanel();
		JButton cancel = new JButton("Cancel");
		JButton ok = new JButton("   Ok   ");
		
		cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ThresholdWindow.this.dispose();
			}
		});
		
		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				try {
					ThresholdPrefs.set(val);
					Logger.log("ThreshholdWindow value changed to " + val);
					ThresholdWindow.this.dispose();
					
				} catch (IOException e) {
					JOptionPane.showMessageDialog(null, "Error occured while saving: " + e.getMessage());
				}
			}
		});
		
		buttons.add(cancel);
		buttons.add(ok);
		
		add(buttons, BorderLayout.SOUTH);
		
		updateLabel();
		
		
		setSize(300,100);
		setVisible(true);
		setResizable(false);
	}
	
	private void updateLabel() {
		progress.setText(val+"%");
	}

	@Override
	public void stateChanged(ChangeEvent arg0) {
		val = ((JSlider)arg0.getSource()).getValue();
		updateLabel();
		
	}
	
	
}
